package com.woodws.sys.security;

import com.woodws.core.util.PasswordUtil;
import com.woodws.sys.entity.AccountInfo;
import com.woodws.sys.entity.SysAccount;
import com.woodws.sys.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

@Component
public class LoginAuthenticationProvider implements AuthenticationProvider {

    @Resource(name = "userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    @Autowired
    private AccountService accountService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        String passwordEnc = PasswordUtil.generateEncodedPassword(password);
        SysAccount account = accountService.findByUsername(username);
        if (account == null || !password.equals(passwordEnc)) {
            throw new BadCredentialsException("用户名密码错误");
        }
        AccountInfo accountInfo = (AccountInfo) userDetailsService.loadUserByUsername(username);

        Collection<? extends GrantedAuthority> authorities = accountInfo.getAuthorities();
        return new UsernamePasswordAuthenticationToken(accountInfo, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }

}